package com.exam.system.config.security;

import com.exam.system.entity.SysUser;
import com.exam.system.service.SysUserServiceimpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @Author LY
 * @create 2023/10/7 10:08
 * @Description security登录
 */
@Component
@Slf4j
public class SecurityUserDetailsService implements UserDetailsService {

    @Autowired
    private SysUserServiceimpl sysUserServiceimpl;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("登录用户：{}", username);
        try {
//            List<GrantedAuthority> authorities = new ArrayList<>();
//            authorities.add(new SimpleGrantedAuthority("ADMIN"));
//            authorities.add(new SimpleGrantedAuthority("ADMIN2"));
//            authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
//            authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN2"));
//            SecurityUserDetails user = new SecurityUserDetails(username, "admin",
//                    "{noop}admin", authorities,
//                    true, true, true, true);

            SecurityUserDetails user = fillAuthorities(username);
            log.info("登录用户信息：{}", user);
            return user;
        } catch (Exception e) {
            String msg = "Username: " + username + " not found";
            log.error(msg, e);
            throw new UsernameNotFoundException(msg);
        }
    }

    /**
     * 填充用户信息及权限角色信息
     * @param username
     * @return
     */
    public SecurityUserDetails fillAuthorities(String username){
        List<GrantedAuthority> authorities = new ArrayList<>();
        // 获取用户角色信息
        SysUser sysUser = sysUserServiceimpl.findSysUser(username);
        authorities.add(new SimpleGrantedAuthority(sysUser.getRole()));
        List<String> list = sysUserServiceimpl.getSysUserPerms(username);
        list.stream().forEach(str -> authorities.add(new SimpleGrantedAuthority(str)));
        SecurityUserDetails user = new SecurityUserDetails(username, sysUser.getUsername(),
                sysUser.getPassword(), authorities,
                true, true, true, true);
        return user;
    }

}
